import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class PriceAnalyzer {
    public static void main(String[] args) {
        File file = new File("D:\\java作业\\2024 云班课\\src\\商品列表.txt");
        Scanner sc = null;
        double sum = 0;
        int count = 0;
        try {
            sc = new Scanner(file);
            sc.useDelimiter("[^0123456789.]+");
            while (sc.hasNext()) {
                try {
                    double price = sc.nextDouble();
                    count++;
                    sum = sum + price;
                    System.out.println(price);
                } catch (InputMismatchException exp) {
                    String t = sc.next();
                }
            }
            double averagePrice = sum / count;
            System.out.println("平均价格:" + averagePrice +"元");

            // 将平均价格追加到原文件
            try (FileWriter writer = new FileWriter(file, true)) {
                writer.write("\n平均价格: " + averagePrice +"元");
            } catch (IOException e) {
                System.out.println("写入文件时出现错误：" + e.getMessage());
            }
        } catch (Exception exp) {
            System.out.println(exp);
        } finally {
            if (sc!= null) {
                sc.close();
            }
        }
    }
}